package ch.bluepenguin.jcr.groovy.builder;

import javax.jcr.Session
import javax.jcr.Node


class JcrBuilder extends BuilderSupport {
	Session session
	Node parentNode
  def log

    public JcrBuilder() {
        super()

    }
  
	//trigger: foo()
	//return: Node
	def createNode(name) {
		checkParentNode()
		parentNode = parentNode.addNode(name)
      if(log) log "added node $name"
		return parentNode
	}

	//trigger: foo('x')
	//return: Object
	// creates node with value=nodetype
	def createNode(name, value) {
		checkParentNode()
		parentNode = parentNode.addNode(name, (String)value)
      if(log) log "added node $name with type $value"
		return parentNode
	}

	//trigger: foo(a:1)
	//return: Object
	def createNode(name, Map attributes) {

        Node node = createNode(name)
		attributes.each { key, value ->
			node.setProperty(key, value)
		}
		return node
	}

	//trigger: foo(a:1, 'x')
	//return: Object
	def createNode(name, Map attributes, value) {
		checkParentNode()
        Node node = createNode(name, value)
            attributes.each { key, myvalue ->
                if(myvalue instanceof Calendar) {
//this is needed because in groovy a java.util.GregorianCalendar is created for Calendar.instance
                    node.setProperty(key, (Calendar)myvalue)
                }  else {
                    node.setProperty(key, myvalue)
                }
            }
        return null
	}

	//trigger: createNode(...) finished
	def void setParent(parent, child) {

	}

	//trigger: recursive closure call finished
	void nodeCompleted(parent, node) {
        session.save()
        parentNode = parentNode.getParent()
	}

	private checkParentNode() {
		if(parentNode==null) parentNode = session.getRootNode()
	}
}